package com.rxt.thermopro.ex

import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import java.io.File

object MediaIntentHelper {
    private fun getUri(cr: ContentResolver, path: String): Uri? {
        var cursor: Cursor? = null
        try {
            val mediaUri = MediaStore.Files.getContentUri("external")
            cursor = cr.query(
                mediaUri,
                arrayOf(MediaStore.MediaColumns._ID),
                MediaStore.MediaColumns.DATA + "=?",
                arrayOf(path),
                null
            )
            if (cursor != null && cursor.moveToFirst()) {
                val id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
                return MediaStore.Files.getContentUri("external", id.toLong())
            }
        } catch (e: Exception) {
            //do ?
        } finally {
            cursor?.close()
        }
        return null
    }

    fun getUri(context: Context, path:String): Uri?{
        return if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            getUri(context.contentResolver, path)
        }else{
            Uri.fromFile(File(path))
        }
    }
    fun view(context: Context, path:String, isVideo:Boolean){
        //val uri = getUri(context.contentResolver, path)
        val uri = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            getUri(context.contentResolver, path)
        }else{
            Uri.fromFile(File(path))
        }
        Intent(Intent.ACTION_VIEW).apply {
            type = if(isVideo) "video/*" else "image/*"
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            data = uri//FileProvider.getUriForFile(context
            //,"${BuildConfig.APPLICATION_ID}.fileProvider"
            //,File(path)
            //)
            context.startActivity(this)
        }
    }
}